package net.oschina.git.fsppp.common.base;

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by QiHuang on 2016/10/7.
 */
public abstract class BaseFrame<T extends BasePresenter, E extends BaseModel> extends JFrame {
    public T mPresenter;
    public E mModel;
    public BaseFrame preFrame;
    public int resultCode;

    /**
     * 普通窗口
     */
    public final static int NORMAL_WIDTH = 800;
    public final static int NORMAL_HEIGHT = 685;

    /**
     * 小窗口
     */
    public final static int SMALL_WIDTH = 800;
    public final static int SMALL_HEIGHT = 600;

    public BaseFrame() {
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                if (mPresenter != null) {
                    mPresenter.onDestroy();
                    mPresenter = null;
                }
                childDoClose();
            }
        });
        initPM();
        if (mPresenter != null) {
            mPresenter.mFrame = this;
        }
        initView();
        this.setVisible(true);
        this.setResizable(false);
        this.setLocation(350, 50);
        this.setTitle(getFrameTitle());
        initListener();
    }

    protected abstract void initView();

    protected abstract void initPM();

    protected abstract void initListener();

    protected abstract String getFrameTitle();

    public void showMsg(String msg) {
        JOptionPane.showMessageDialog(this, msg, "tip", JOptionPane.INFORMATION_MESSAGE);
    }

    public String showInputDialog(String defaultName) {
        return JOptionPane.showInputDialog(this, "输入名称", defaultName);
    }

    public int showComfirmDialog(String msg) {
        return JOptionPane.showConfirmDialog(this, msg, "tip", JOptionPane.YES_NO_OPTION);
    }

    public int showSelectDialog(String[] items, String msg) {
        String s = (String) JOptionPane.showInputDialog(this, msg, "tip", JOptionPane.PLAIN_MESSAGE, null, items, items[0]);
        for (int i = 0; i < items.length; i++) {
            if (s.equals(items[i])) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 子类重写用来获取其他窗口的回调信息
     * @param resultCode
     */
    public void onFrameResult(int resultCode) {

    }

    public void refresh() {
        this.repaint();
        this.validate();
        this.invalidate();
        this.validate();
    }

    /**
     * 子类窗口点击事件
     */
    protected void childDoClose() {
    }
}
